package com.etbsms.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.etbsms.dao.IFilesDAO;
import com.etbsms.domain.Files;
import com.etbsms.service.IFilesService;

@Service
@Component("filesService")
public class FilesServiceImpl implements IFilesService {

	@Autowired
	private IFilesDAO filesDAO;

	@Override
	public boolean save(Files entity) {
		
		
		CommonsMultipartFile f = entity.getFileData();		
		entity.setOriginal_name(f.getOriginalFilename());
		entity.setSize(f.getSize());
		entity.setEnabled(true);
		entity.setUpload_time(new Date());		
		String uid = UUID.randomUUID().toString().replaceAll("-", "");		
		String folder = String.valueOf(entity.getUpdate_user()) + "/" + uid;		
		
		
		File absolute_path = new File(entity.getRoot_folder(),folder);
		if(!absolute_path.getParentFile().exists())
			absolute_path.getParentFile().mkdirs();
		
		//entity.setPath(absolute_path.getAbsolutePath());
		entity.setStored_name(uid);
		
		try {
			f.transferTo(absolute_path);
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
		return filesDAO.save(entity);
	}

	@Override
	public Files get(Integer seq_no) {
		// TODO Auto-generated method stub
		return filesDAO.get(seq_no);
	}
	
	
}
